package com.dhl.fin.api.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.dhl.fin.api.common.authentication.TokenService;
import com.dhl.fin.api.common.dto.ApiResponse;
import com.dhl.fin.api.common.dto.QueryDto;
import com.dhl.fin.api.common.dto.UserInfo;
import com.dhl.fin.api.common.enums.EnvType;
import com.dhl.fin.api.common.enums.LoginStatus;
import com.dhl.fin.api.common.exception.BusinessException;
import com.dhl.fin.api.common.exception.LoginException;
import com.dhl.fin.api.common.util.ObjectUtil;
import com.dhl.fin.api.common.util.StringUtil;
import com.dhl.fin.api.common.util.WebUtil;
import com.dhl.fin.api.domain.Account;
import com.dhl.fin.api.domain.Project;
import com.dhl.fin.api.domain.Tree;
import com.dhl.fin.api.dto.LoginResponse;
import com.dhl.fin.api.service.AccountServiceImpl;
import com.dhl.fin.api.service.LdapAuthenticationService;
import com.dhl.fin.api.service.LoginServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private AccountServiceImpl accountService;

    @Autowired
    private LoginServiceImpl loginService;


    @Value("${spring.profiles.active}")
    private String profiles;


    @CrossOrigin
    @RequestMapping("/login")
    public ApiResponse loginUser(String password, String userName) {
        try {
            LoginResponse loginResponse;
            if (StringUtil.isNotEmpty(userName) && userName.equals("admin")) {
                loginResponse = adminLogin();
            } else {
                loginResponse = userLogin(password, userName);
            }
            return ApiResponse.success(loginResponse);
        } catch (BusinessException e) {
            return ApiResponse.error(e.getMessage());
        }  catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error("后台异常，登录失败");
        }

    }

    @RequestMapping("/loginout")
    public ApiResponse loginOut() {
        return new ApiResponse();
    }

    @RequestMapping("/user")
    public ApiResponse user() {
        return ApiResponse.success(WebUtil.getLoginUser());
    }


    public void setDefaultUrl(LoginResponse loginResponse, String userName) throws Exception {
        List<Project> projects = accountService.getProjectsByUUID(userName);
        Map<String, List<Tree>> menus = accountService.getMenuTreePerProject(userName);
        String defaultRouteUrl = "/menu";
        Map<String, String> urlParams = new HashMap<>();
        if (CollectionUtil.isNotEmpty(menus) && CollectionUtil.isNotEmpty(projects)) {
            String projectCode = projects.get(0).getCode();
            String routePath = "";
            List<Tree> projectMenus = menus.get(projectCode);
            if (CollectionUtil.isNotEmpty(projectMenus)) {
                List<Tree> childrenMenu = projectMenus.get(0).getChildren();
                if (CollectionUtil.isNotEmpty(childrenMenu)) {
                    routePath = childrenMenu.get(0).getMenu().getClickUrl();
                } else {
                    routePath = projectMenus.get(0).getMenu().getClickUrl();
                }
            }
            defaultRouteUrl = StringUtil.join(projectCode.toLowerCase(), "/", routePath);
            urlParams.put("m_c", projectCode);
        }

        loginResponse.setRouteUrl(defaultRouteUrl);
        loginResponse.setUrlParams(urlParams);

    }

    public LoginResponse adminLogin() throws Exception {
        LoginResponse loginResponse = new LoginResponse();

        setDefaultUrl(loginResponse, "admin");

        UserInfo userInfo = UserInfo.builder()
                .uuid("admin")
                .userName("admin")
                .defaultRoute(loginResponse.getRouteUrl())
                .build();
        loginResponse.setStatus(LoginStatus.SUCCESS.getStatus());
        loginResponse.setToken(tokenService.generateToken(userInfo));
        loginResponse.setUuid("admin");
        loginResponse.setUserName("admin");
        return loginResponse;
    }

    public LoginResponse userLogin(String password, String userName) throws Exception {

        LoginResponse loginResponse = new LoginResponse();
        boolean isLogin = false;

        Account loginAccount = accountService.get(
                QueryDto.builder()
                        .available()
                        .addJoinDomain("roles")
                        .addWhere(String.format("account.uuid='%s'", userName))
                        .addWhere(String.format("account.available=1"))
                        .build()
        );

        if (ObjectUtil.isNull(loginAccount)) {
            String logInfo = "不存此账号：" + userName;
            log.info(logInfo);
            throw new LoginException(logInfo);
        }


        if (EnvType.PROD.getType().equalsIgnoreCase(profiles)) {
            if (StringUtil.isEmpty(password)) {
                loginResponse.setStatus(LoginStatus.VERIFICATIONFAILED.getStatus());
                throw new LoginException("密码不能为空");
            } else {
                if (LdapAuthenticationService.auth(userName, password)) {
                    isLogin = true;
                } else {
                    String errorInf = String.format("用户名或密码错误（%s）", userName);
                    log.info(errorInf);
                    throw new LoginException(errorInf);
                }
            }
        } else {
            isLogin = true;
        }


        if (isLogin) {
            setDefaultUrl(loginResponse, loginAccount.getUuid());
            UserInfo userInfo = UserInfo.builder()
                    .uuid(loginAccount.getUuid())
                    .userName(loginAccount.getName())
                    .defaultRoute(loginResponse.getRouteUrl())
                    .build();
            loginResponse.setStatus(LoginStatus.SUCCESS.getStatus());
            loginResponse.setToken(tokenService.generateToken(userInfo));
            loginResponse.setUuid(userInfo.getUuid());
            loginResponse.setUserId(loginAccount.getId().toString());
            loginResponse.setUserName(userInfo.getUserName());
        }

        log.info("登录成功：" + userName);
        return loginResponse;
    }


    @ResponseBody
    @RequestMapping("acctdata")
    public ApiResponse getAccountInfo() {
        try {
            Map acctData = loginService.getLoginUserPermission();
            return ApiResponse.success(acctData);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ApiResponse.error("获取人员权限信息失败");
    }

}


